<template>
  <div class="main">
    <div>
      <el-input v-model="keyword" placeholder="用户名" style="width:200px;margin-right:10px;"></el-input>
      <el-button type="primary" icon="el-icon-search" @click="getSearch">搜索</el-button>
      <el-button @click="clear">清空</el-button>
    </div>
    <div style="margin-top:10px">
      <el-button type="primary" @click="showAdd">添加</el-button>
      <el-button type="danger" @click="delUser('')">批量删除</el-button>
    </div>

    <!-- //添加表单弹出框 -->
    <el-dialog :title="form.id?'修改用户':'添加用户'" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="ruleForm" v-loading="loading">
        <el-form-item label="用户名称" label-width="100px" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" label-width="100px">
          <el-input v-model="form.nickName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" label-width="100px" prop="password" v-show="!form.id">
          <el-input type="password" v-model="form.password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addUser('ruleForm')">{{!form.id?"添 加":"修 改"}}</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-table
      ref="multipleTable"
      tooltip-effect="dark"
      style="margin-top:10px"
      @selection-change="handleSelectionChange"
      border
      :data="users"
    >
      <el-table-column align="center" type="selection" width="55"></el-table-column>
      <el-table-column align="center" type="index" label="序号" width="90"></el-table-column>
      <el-table-column prop="username" label="用户名" width="120"></el-table-column>
      <el-table-column prop="nickName" label="用户昵称" width="120"></el-table-column>
      <el-table-column prop="roleName" label="用户权限"></el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间"></el-table-column>
      <el-table-column prop="gmtModified" label="更新时间"></el-table-column>
      <el-table-column prop="prop" label="操作">
        <template slot-scope="{row}">
          <el-button type="info" icon="el-icon-user" size="mini" @click="showEdit(row.id)"></el-button>
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showUpdate(row.id)"></el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="delUser(row.id)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- //添加表单弹出框 -->
    <el-dialog title="修改权限" :visible.sync="dialogEditVisible">
      <el-form>
        <el-form-item label="用户名称" label-width="100px">
          <el-input v-model="form.username" readonly disabled></el-input>
        </el-form-item>
        <el-form-item label="角色列表" label-width="100px">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
          >全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="checkeds" @change="handleCheckedChange">
            <el-checkbox
              v-for="role in roles"
              :label="role"
              :key="role.id"
              :checked="role.check==1"
            >{{role.roleName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doAssign">分 配</el-button>
        <el-button @click="closeAssign">取 消</el-button>
      </div>
    </el-dialog>

    <el-pagination
      align="center"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[3, 5, 7, 9]"
      :page-size="size"
      layout=" prev, pager, next, jumper,->,total, sizes"
      :total="total"
    ></el-pagination>
  </div>
</template>

<script>
export default {
  name: "User",
  data() {
    var validateName = (rule, value, callback) => {
      if (value.length>3) {
        return callback(new Error("用户名至少3个字符"));
      }
      callback();
    };
    var validatePass = (rule, value, callback) => {
      if (!value.trim()) {
        return callback(new Error("密码不能为空"));
      }
      if (value.trim().length < 6) {
        return callback(new Error("密码不能少于6位"));
      }
      callback();
    };
    return {
      keyword: "",
      search: {},
      multipleSelection: [],
      page: 1,
      size: 5,
      total: 0,
      users: [],
      dialogFormVisible: false,
      dialogEditVisible: false,
      form: {
        username: "",
        nickName: "",
        password: ""
      },
      loading: false,
      rules: {
        username: [
          { required: true, message: "用户名必须输入" },
          { validator: validateName, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }]
      },
      checkAll: false,
      checkeds: [],
      isIndeterminate: true,
      roles: []
    };
  },
  mounted() {
    this.getUser();
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    //分页操作
    handleSizeChange(val) {
      (this.size = val), this.getUser();
    },
    handleCurrentChange(val) {
      (this.page = val), this.getUser();
    },
    //获取用户列表
    async getUser() {
      let result = await this.$api.default.user.getUser(
        this.page,
        this.size,
        this.search
      );
      if (result.code == 20000) {
        this.users = result.data.items;
        this.total = result.data.total;
      }
    },
    //搜索
    getSearch() {
      this.search.username = this.keyword;
      this.getUser();
    },
    //清空搜索框
    clear() {
      this.keyword = "";
      this.search.username = "";
      this.getUser();
    },

    //打开添加用户界面
    showAdd() {
      this.loading = false;
      this.dialogFormVisible = true;
      this.form = {};
      this.$nextTick(() => this.$refs.ruleForm.clearValidate());
    },

    //添加用户
    addUser(ruleForm) {
      this.$refs[ruleForm].validate(async valid => {
        try {
          if (valid) {
            this.loading = true;
            let result = await this.$api.default.user[
              !this.form.id ? "addUser" : "updateUser"
            ](this.form);
            if (result.code == 20000) {
              this.loading = false;
              this.getUser();
              this.dialogFormVisible = false;
              this.$message({
                type: "success",
                message: "操作成功!"
              });
            }
            this.form = {};
          } else {
            this.$message({
              type: "danger",
              message: "操作失败!"
            });
            return false;
          }
        } catch (error) {
          this.loading = false;
          this.$message({
            type: "info",
            message: "名字重复,请重新重试!"
          });
          return;
        }
      });
    },

    //删除用户
    async delUser(id) {
      let results = [];
      if (id) {
        let result = await this.$api.default.user.delUser(id);
        if (result.code == 20000) {
          this.getUser();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        } else {
          this.$message({
            type: "error",
            message: "删除失败!"
          });
        }
      } else {
        for (let m of this.multipleSelection) {
          let result = await this.$api.default.user.delUser(m.id);
          results.push(result);
        }
        Promise.all(results)
          .then(rej => {
            this.getUser();
            this.$message({
              type: "success",
              message: "删除成功!"
            });
          })
          .catch(error => {
            this.$message({
              type: "error",
              message: "删除失败!"
            });
          });
      }
    },

    //修改用户权限
    async showEdit(id) {
      let result = await this.$api.default.user.getUserById(id);
      if (result.code == 20000) {
        this.form = result.data.item;
      }
      result = await this.$api.default.user.getUserRoleInfo(this.form.id);
      if (result.code == 20000) {
        let roles = result.data.allRolesList;
        let rolesCheck = result.data.assignRoles;
        roles.forEach(item => {
          if (rolesCheck.some(it => item.id == it.id)) {
            item.check = 1;
          }
        });
        this.roles = roles;
      }
      this.dialogEditVisible = true;
    },

    //多选操作
    handleCheckAllChange(val) {
      console.log(val);
      this.checkeds = val ? this.roles : [];
      this.isIndeterminate = false;
    },
    handleCheckedChange(value) {
      console.log(value);
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.roles.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.roles.length;
    },

    //关闭分配窗口
    closeAssign() {
      this.checkeds = [];
      this.roles = [];
      this.dialogEditVisible = false;
    },
    //分配角色
    async doAssign() {
      let roleId = this.checkeds.map(item => {
        return item.id;
      });
      roleId = roleId.join(",");
      let result = await this.$api.default.user.userDoAssign(
        this.form.id,
        roleId
      );
      if (result.code == 20000) {
        this.getUser();
        this.dialogEditVisible = false;
        (this.checkeds = []), (this.form = {});
        this.$message({
          type: "success",
          message: "分配成功!"
        });
      }
    },

    //修改用户页面
    async showUpdate(id) {
      let result = await this.$api.default.user.getUserById(id);
      if (result.code == 20000) {
        this.form = result.data.item;
      }
      this.dialogFormVisible = true;
    }
  }
};
</script>

<style>
.main {
  padding: 20px;
}
</style>